<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Rust Browser</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            display: flex;
            flex-direction: column;
            height: 100vh;
            background: #f5f5f5;
        }

        .tabs-bar {
            display: flex;
            background: #e8e8e8;
            padding: 5px 5px 0 5px;
            gap: 2px;
            overflow-x: auto;
            border-bottom: 1px solid #ccc;
        }

        .tab {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: #d0d0d0;
            border: 1px solid #bbb;
            border-bottom: none;
            border-radius: 6px 6px 0 0;
            cursor: pointer;
            min-width: 150px;
            max-width: 250px;
            transition: background 0.2s;
        }

        .tab:hover {
            background: #c0c0c0;
        }

        .tab.active {
            background: #fff;
            border-color: #ccc;
        }

        .tab-title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 13px;
        }

        .tab-close {
            padding: 2px 6px;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 16px;
            color: #666;
            border-radius: 3px;
        }

        .tab-close:hover {
            background: #ff5555;
            color: white;
        }

        .new-tab-btn {
            padding: 8px 15px;
            background: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 6px 6px 0 0;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.2s;
        }

        .new-tab-btn:hover {
            background: #e0e0e0;
        }

        .toolbar {
            display: flex;
            align-items: center;
            padding: 10px;
            background: #fff;
            border-bottom: 1px solid #ddd;
            gap: 10px;
        }

        .nav-buttons {
            display: flex;
            gap: 5px;
        }

        .nav-btn {
            padding: 8px 12px;
            background: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.2s;
        }

        .nav-btn:hover {
            background: #e0e0e0;
        }

        .nav-btn:active {
            background: #d0d0d0;
        }

        .nav-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .url-bar {
            flex: 1;
            display: flex;
            gap: 5px;
        }

        #urlInput {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
        }

        #urlInput:focus {
            outline: none;
            border-color: #0066cc;
        }

        .go-btn {
            padding: 8px 20px;
            background: #0066cc;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s;
        }

        .go-btn:hover {
            background: #0052a3;
        }

        .content {
            flex: 1;
            position: relative;
            overflow: hidden;
        }

        .webview-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: none;
        }

        .webview-container.active {
            display: block;
        }

        .webview {
            width: 100%;
            height: 100%;
            border: none;
            background: white;
        }

        .status-bar {
            padding: 5px 10px;
            background: #fff;
            border-top: 1px solid #ddd;
            font-size: 12px;
            color: #666;
        }

        .home-btn {
            padding: 8px 12px;
            background: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.2s;
        }

        .home-btn:hover {
            background: #e0e0e0;
        }
    </style>
</head>
<body>
    <div class="tabs-bar" id="tabsBar">
        <button class="new-tab-btn" id="newTabBtn" title="新建标签页">+</button>
    </div>

    <div class="toolbar">
        <div class="nav-buttons">
            <button class="nav-btn" id="backBtn" title="后退">←</button>
            <button class="nav-btn" id="forwardBtn" title="前进">→</button>
            <button class="nav-btn" id="refreshBtn" title="刷新">⟳</button>
            <button class="home-btn" id="homeBtn" title="主页">🏠</button>
        </div>
        <div class="url-bar">
            <input type="text" id="urlInput" placeholder="输入网址 (例如: https://www.google.com)" />
            <button class="go-btn" id="goBtn">访问</button>
        </div>
    </div>
    
    <div class="content" id="content"></div>
    
    <div class="status-bar" id="statusBar">就绪</div>

    <script>
        const urlInput = document.getElementById('urlInput');
        const statusBar = document.getElementById('statusBar');
        const goBtn = document.getElementById('goBtn');
        const backBtn = document.getElementById('backBtn');
        const forwardBtn = document.getElementById('forwardBtn');
        const refreshBtn = document.getElementById('refreshBtn');
        const homeBtn = document.getElementById('homeBtn');
        const newTabBtn = document.getElementById('newTabBtn');
        const tabsBar = document.getElementById('tabsBar');
        const content = document.getElementById('content');

        const homePage = 'https://www.baidu.com/';
        let tabIdCounter = 0;
        let tabs = [];
        let activeTabId = null;

        class Tab {
            constructor(url = homePage) {
                this.id = ++tabIdCounter;
                this.url = url;
                this.title = 'New Tab';
                this.history = [];
                this.currentIndex = -1;
                this.createElement();
                this.navigate(url);
            }

            createElement() {
                // 创建标签元素
                this.tabElement = document.createElement('div');
                this.tabElement.className = 'tab';
                this.tabElement.innerHTML = `
                    <span class="tab-title">${this.title}</span>
                    <button class="tab-close">×</button>
                `;
                
                this.tabElement.querySelector('.tab-title').addEventListener('click', () => {
                    switchTab(this.id);
                });
                
                this.tabElement.querySelector('.tab-close').addEventListener('click', (e) => {
                    e.stopPropagation();
                    closeTab(this.id);
                });

                // 创建 webview 容器
                this.container = document.createElement('div');
                this.container.className = 'webview-container';
                this.webview = document.createElement('iframe');
                this.webview.className = 'webview';
                this.webview.sandbox = 'allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation';
                
                this.container.appendChild(this.webview);
                content.appendChild(this.container);

                // 监听加载事件
                this.webview.addEventListener('load', () => {
                    this.updateTitle();
                    this.setupLinkInterception();
                    if (this.id === activeTabId) {
                        statusBar.textContent = '页面加载完成';
                    }
                });

                tabsBar.insertBefore(this.tabElement, newTabBtn);
            }

            setupLinkInterception() {
                try {
                    const iframeDoc = this.webview.contentDocument || this.webview.contentWindow.document;
                    if (!iframeDoc) return;

                    // 拦截所有链接点击
                    iframeDoc.addEventListener('click', (e) => {
                        let target = e.target;
                        
                        // 向上查找，找到 <a> 标签
                        while (target && target.tagName !== 'A') {
                            target = target.parentElement;
                        }
                        
                        if (target && target.tagName === 'A' && target.href) {
                            const href = target.href;
                            const targetAttr = target.getAttribute('target');
                            
                            // 阻止默认行为，防止使用 shell.open
                            e.preventDefault();
                            
                            // 如果是 target="_blank" 或者按住 Ctrl/Cmd 键，在新标签页打开
                            if (targetAttr === '_blank' || e.ctrlKey || e.metaKey) {
                                createTab(href);
                            } else {
                                // 在当前标签页导航
                                this.navigate(href);
                            }
                        }
                    }, true);

                    // 监听鼠标中键点击
                    iframeDoc.addEventListener('auxclick', (e) => {
                        if (e.button === 1) { // 中键
                            let target = e.target;
                            while (target && target.tagName !== 'A') {
                                target = target.parentElement;
                            }
                            if (target && target.tagName === 'A' && target.href) {
                                e.preventDefault();
                                createTab(target.href);
                            }
                        }
                    }, true);

                } catch (error) {
                    // 跨域限制，无法访问 iframe 内容
                    console.log('Cannot intercept links due to cross-origin restrictions');
                }
            }

            navigate(url) {
                const normalizedUrl = normalizeUrl(url);
                if (!normalizedUrl) return;
                
                this.webview.src = normalizedUrl;
                this.url = normalizedUrl;
                
                if (this.currentIndex < this.history.length - 1) {
                    this.history = this.history.slice(0, this.currentIndex + 1);
                }
                this.history.push(normalizedUrl);
                this.currentIndex = this.history.length - 1;
                
                if (this.id === activeTabId) {
                    urlInput.value = normalizedUrl;
                    statusBar.textContent = `正在加载: ${normalizedUrl}`;
                    updateNavigationButtons();
                }
            }

            updateTitle() {
                try {
                    const title = this.webview.contentDocument?.title || new URL(this.url).hostname;
                    this.title = title || 'New Tab';
                    this.tabElement.querySelector('.tab-title').textContent = this.title;
                } catch (e) {
                    this.title = new URL(this.url).hostname;
                    this.tabElement.querySelector('.tab-title').textContent = this.title;
                }
            }

            activate() {
                this.tabElement.classList.add('active');
                this.container.classList.add('active');
                urlInput.value = this.url;
                updateNavigationButtons();
            }

            deactivate() {
                this.tabElement.classList.remove('active');
                this.container.classList.remove('active');
            }

            destroy() {
                this.tabElement.remove();
                this.container.remove();
            }

            goBack() {
                if (this.currentIndex > 0) {
                    this.currentIndex--;
                    this.url = this.history[this.currentIndex];
                    this.webview.src = this.url;
                    urlInput.value = this.url;
                    updateNavigationButtons();
                }
            }

            goForward() {
                if (this.currentIndex < this.history.length - 1) {
                    this.currentIndex++;
                    this.url = this.history[this.currentIndex];
                    this.webview.src = this.url;
                    urlInput.value = this.url;
                    updateNavigationButtons();
                }
            }

            refresh() {
                const currentSrc = this.webview.src;
                this.webview.src = '';
                setTimeout(() => {
                    this.webview.src = currentSrc;
                    statusBar.textContent = '正在刷新...';
                }, 10);
            }
        }

        function normalizeUrl(url) {
            url = url.trim();
            if (!url) return '';
            
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                if (url.includes(' ') || (!url.includes('.') && !url.includes('localhost'))) {
                    return 'https://www.google.com/search?q=' + encodeURIComponent(url);
                }
                url = 'https://' + url;
            }
            return url;
        }

        function createTab(url = homePage) {
            const tab = new Tab(url);
            tabs.push(tab);
            switchTab(tab.id);
            return tab;
        }

        function switchTab(tabId) {
            const tab = tabs.find(t => t.id === tabId);
            if (!tab) return;

            if (activeTabId !== null) {
                const currentTab = tabs.find(t => t.id === activeTabId);
                if (currentTab) currentTab.deactivate();
            }

            activeTabId = tabId;
            tab.activate();
        }

        function closeTab(tabId) {
            const index = tabs.findIndex(t => t.id === tabId);
            if (index === -1) return;

            const tab = tabs[index];
            tab.destroy();
            tabs.splice(index, 1);

            if (tabs.length === 0) {
                createTab();
            } else if (activeTabId === tabId) {
                const newActiveIndex = Math.min(index, tabs.length - 1);
                switchTab(tabs[newActiveIndex].id);
            }
        }

        function getActiveTab() {
            return tabs.find(t => t.id === activeTabId);
        }

        function updateNavigationButtons() {
            const tab = getActiveTab();
            if (!tab) return;
            
            backBtn.disabled = tab.currentIndex <= 0;
            forwardBtn.disabled = tab.currentIndex >= tab.history.length - 1;
        }

        // 事件监听
        newTabBtn.addEventListener('click', () => createTab());

        goBtn.addEventListener('click', () => {
            const tab = getActiveTab();
            if (tab && urlInput.value) {
                tab.navigate(urlInput.value);
            }
        });

        urlInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const tab = getActiveTab();
                if (tab && urlInput.value) {
                    tab.navigate(urlInput.value);
                }
            }
        });

        backBtn.addEventListener('click', () => {
            const tab = getActiveTab();
            if (tab) tab.goBack();
        });

        forwardBtn.addEventListener('click', () => {
            const tab = getActiveTab();
            if (tab) tab.goForward();
        });

        refreshBtn.addEventListener('click', () => {
            const tab = getActiveTab();
            if (tab) tab.refresh();
        });

        homeBtn.addEventListener('click', () => {
            const tab = getActiveTab();
            if (tab) tab.navigate(homePage);
        });

        // 初始化第一个标签页
        createTab();
    </script>
</body>
</html>